package com.bi.test1;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bi.test1.bean.ScreenBean;
import com.bi.test1.utils.LocUtil;

import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.utils.Log;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;

//在原来的基础上 增加了横竖屏判断实现了   controller中增加了reset功能以及构造函数（指定出现位置）  隐藏了seekbar等控件   VideoView中更改surfaceHolder宽高
//竖屏显示其他布局   横屏隐藏其它布局解决 全屏时controller不在底部问题
//增加了全屏按钮（利用接口回调将事件从controller传到VideoView再传到PlayActivity）
//增加了加载时的图片 设置VideoView的背景为纯黑 播放时设为透明  避免一开始进入时的透明状态
public class PlayActivity extends Activity implements VideoView.ActionInterface {
    /** 当前视频路径 */
    private String path ="rtmp://live.hkstv.hk.lxdns.com/live/hks";

    //private String path ="http://mvvideo1.meitudata.com/5704a8ffdf7b14102.mp4";
    //private String path ="rtmp://192.168.201.209:1935/live1/13718757521";
    //private String path ="http://hls1a.douyutv.com/live/14163r3n6lo4pHLZ/playlist.m3u8?wsSecret=22677ee2bb0b380837fe57a5d23756d4&wsTime=1465292078";
            //gESD--->/storage/emulated/0     gESPD--->/storage/emulated/0/Music
   // private String path ="http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8";
    /** 当前声音 */
    private int mVolume = -1;
    /** 最大音量 */
    private int mMaxVolume;
    /** 当前亮度 */
    private float mBrightness = -1f;
    /** 手势数目 */
    private int finNum=0;

    private View mVolumeBrightnessLayout;
    private ImageView mOperationBg;
    private ImageView mOperationPercent;
    private VideoView mVideoView;
    private GestureDetector gestDetector;
    private ScaleGestureDetector scaleDetector;

    private ScreenBean screenBean;

    private Button btn;
    private View fl_Video,ll_Play;
    private TextView iv_fl_video;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        if (!LibsChecker.checkVitamioLibs(this))
            return;

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_play);


        init();
    }

    @Override//************************
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            ImageButton imageButton= mVideoView.getFullButton();
            imageButton.setImageResource(R.mipmap.ic_fullscreen_pre);

            int mOrientation = PlayActivity.this.getResources().getConfiguration().orientation;
            if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
                PlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                ll_Play.setVisibility(View.VISIBLE);
                //恢复到原来的情况
                mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void init() {
        ll_Play=findViewById(R.id.ll_Play);
        fl_Video=findViewById(R.id.fl_Video);
        iv_fl_video= (TextView) findViewById(R.id.iv_fl_Video);

        mVideoView = (VideoView) findViewById(R.id.surface_view);
        mVolumeBrightnessLayout = findViewById(R.id.operation_volume_brightness);
        mOperationBg = (ImageView) findViewById(R.id.operation_bg);
        mOperationPercent = (ImageView) findViewById(R.id.operation_percent);

        mVideoView.setActionListener(this);//**********************

        mMaxVolume = LocUtil.getMaxVolume(this);
        gestDetector = new GestureDetector(this, new SingleGestureListener());
        scaleDetector = new ScaleGestureDetector(this,
                new MultiGestureListener());

        screenBean = LocUtil.getScreenPix(this);
        if (path == "") {
            return;
        } else {
            mVideoView.setVideoPath(path);
            MediaController mc=new MediaController(this,true,fl_Video);
            mVideoView.setMediaController(mc);
            mc.setVisibility(View.GONE);//此操作是为了解决打开视频的时候控制条不走动，需要点击下视频才走动的问题。这样默认情况下用户看不到进度条，当点击视频的时候就可以看到正在走动的进度条了
            mVideoView.requestFocus();

            //mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);

            mVideoView
                    .setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mediaPlayer) {
                            mediaPlayer.setPlaybackSpeed(1.0f);
                        }
                    });

            //默认是1024*1024
            mVideoView.setBufferSize(8);


        }
    }

    private  void fullScreen(ImageButton mFullButton) {
        int mOrientation=PlayActivity.this.getResources().getConfiguration().orientation;
        if(mOrientation== Configuration.ORIENTATION_PORTRAIT) {
            PlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            ll_Play.setVisibility(View.GONE);

            mFullButton.setImageResource(R.mipmap.ic_fullscreen_nor);
            //让视频全屏
            mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
        }else{
            PlayActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            ll_Play.setVisibility(View.VISIBLE);

            mFullButton.setImageResource(R.mipmap.ic_fullscreen_pre);
            //恢复到原来的情况
            mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
        }
    }

    /** 定时隐藏 */
    private Handler mDismissHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mVolumeBrightnessLayout.setVisibility(View.GONE);
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        finNum=event.getPointerCount();

        if (1 == finNum) {
            gestDetector.onTouchEvent(event);
            switch (event.getAction()) {
                case MotionEvent.ACTION_UP:
                    endGesture();
            }
        } else if (2 ==finNum) {
            //TODO 是否取消缩放
           // scaleDetector.onTouchEvent(event);
        }
        return true;
    }

    /** 手势结束 */
    private void endGesture() {
        mVolume = -1;
        mBrightness = -1f;

        // 隐藏
        mDismissHandler.removeMessages(0);
        mDismissHandler.sendEmptyMessageDelayed(0, 500);
    }

    /**
     * 视频缩放
     */
    public void changeLayout(int size) {
        mVideoView.setVideoLayout(size, 0);
    }

    /**
     * 声音大小
     *
     * @param percent
     */
    public void changeVolume(float percent) {
        if (mVolume == -1) {
            mVolume = LocUtil.getCurVolume(this);
            if (mVolume < 0)
                mVolume = 0;
            // 显示
            mOperationBg.setImageResource(R.drawable.video_volumn_bg);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }
        int index = (int) (percent * mMaxVolume) + mVolume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        LocUtil.setCurVolume(this, index);

        // 变更进度条
        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = findViewById(R.id.operation_full).getLayoutParams().width
                * index / mMaxVolume;
        mOperationPercent.setLayoutParams(lp);
    }

    /**
     * 亮度大小
     *
     * @param percent
     */
    public void changeBrightness(float percent) {
        if (mBrightness < 0) {
            mBrightness = getWindow().getAttributes().screenBrightness;
            if (mBrightness <= 0.00f)
                mBrightness = 0.50f;
            if (mBrightness < 0.01f)
                mBrightness = 0.01f;
            // 显示
            mOperationBg.setImageResource(R.drawable.video_brightness_bg);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }

        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        lpa.screenBrightness = mBrightness + percent;
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
        else if (lpa.screenBrightness < 0.01f)
            lpa.screenBrightness = 0.01f;
        getWindow().setAttributes(lpa);

        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = (int) (findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness);
        mOperationPercent.setLayoutParams(lp);
    }


    /**
     * 单点触屏
     *
     * @author jin
     *
     */
    private class SingleGestureListener implements
            GestureDetector.OnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            // TODO Auto-generated method stub
            Log.d("Fling", velocityY);
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            // TODO Auto-generated method stub
            if(2==finNum){
                return false;
            }

            float moldX = e1.getX();
            float moldY = e1.getY();
            float y = e2.getY();
            if (moldX > screenBean.getsWidth() * 9.0 / 10)// 右边滑动
                changeVolume((moldY - y) / screenBean.getsHeight());
            else if (moldX < screenBean.getsWidth() / 10.0)// 左边滑动
                changeBrightness((moldY - y) / screenBean.getsHeight());
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // TODO Auto-generated method stub
            return false;
        }
    }

    /**
     * 多点缩放
     *
     * @author jin
     *
     */
    private class MultiGestureListener implements ScaleGestureDetector.OnScaleGestureListener {

        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            // 返回true ，才能进入onscale()函数
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            float oldDis = detector.getPreviousSpan();
            float curDis = detector.getCurrentSpan();
            if (oldDis - curDis > 50) {
                // 缩小
                changeLayout(0);
                Toast.makeText(PlayActivity.this, "缩小", Toast.LENGTH_SHORT).show();
            } else if (oldDis - curDis < -50) {
                // 放大
                changeLayout(1);
                Toast.makeText(PlayActivity.this, "放大", Toast.LENGTH_SHORT).show();
            }
        }

    }

    @Override
    public void fullAction(ImageButton mFullButton) {
        fullScreen(mFullButton);
    }

    @Override
    public void startPlayAction() {
        mVideoView.setBackgroundResource(R.color.transparent);
        Toast.makeText(PlayActivity.this, "kaishi", Toast.LENGTH_SHORT).show();
        iv_fl_video.setVisibility(View.GONE);
    }

    @Override
    public void prepareAction() {
        Toast.makeText(PlayActivity.this, "prepare", Toast.LENGTH_SHORT).show();
        iv_fl_video.setVisibility(View.VISIBLE);
    }
    @Override
    public void resetAction() {
        Toast.makeText(PlayActivity.this, "reset", Toast.LENGTH_SHORT).show();
        iv_fl_video.setVisibility(View.VISIBLE);
    }

    @Override
    public void dealError() {
        // TODO 处理视频播放不了的问题
    }


}







































/*

public class PlayActivity extends BaseActivity {


    private static final String TAG = "MainActivity";
    private String path;
    // private HashMap<String,String > options;
    private VideoView mVideoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!LibsChecker.checkVitamioLibs(this))
            return;
        setContentView(R.layout.activity_play);
        mVideoView = (VideoView) findViewById(R.id.vitamio_videoView);
        //path = "http://slicer.cchvc.net/hls/17710348553Dest.m3u8";
        // path = "rtmp://106.38.227.68:1935/src/13121575706";
        //  path ="rtmp://rrbalancer.broadcast.tneg.de:1935/pw/ruk/ruk";
         path ="rtmp://live.hkstv.hk.lxdns.com/live/hks";

       */
/* options = new HashMap<>();
        options.put("rtmp_playpath", "");
        options.put("rtmp_swfurl", "");
        options.put("rtmp_live", "1");
        options.put("rtmp_pageurl", "");*//*


        mVideoView.setVideoPath(path);

        //mVideoView.setVideoURI(Uri.parse(path), options);

        mVideoView.setMediaController(new MediaController(this));
        mVideoView.requestFocus();

        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.setPlaybackSpeed(1.0f);
            }
        });

       */
/* mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                switch (what) {
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        if (mVideoView.isPlaying()) {
                            mVideoView.pause();
                        }
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        mVideoView.start();
                        break;
                    case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:

                        break;
                }
                return true;

            }
        });*//*


    }
}
*/
